<template>
  <aside class="leftpanner content_left">
    <div class="actions">
      <Search />
      <p class="network" v-if="!networkState?.online">
        <el-icon color="rgba(247, 76, 49, 1)">
          <Warning />
        </el-icon>
        <span>网络连接已中断</span>
      </p>
      <SearchAddAction />
    </div>
    <ul class="messageContent" :ref="container.ref" @scroll="container.onScroll">
      <div ref="wrapperRef">
        <li draggable="true" @dragstart="dragstart" @click.right="openRightMenu(item)"
          :class="(selectSession?.uuid === item?.uuid) ? 'active' : null" class="message badge"
          v-for="({ data: item }, index) in list" :key="index" @click="selectAction(item)">
          <el-badge :hidden="!(item?.hasRead !== 0 && item?.lastMsg !== '' && item?.disturb === 'Y')" is-dot
            style="flex-shrink: 0;">
            <el-avatar :size="46" :src="item?.msgCustomType === 1 ? item?.groupPortrait : item?.portrait" />
          </el-badge>
          <section class="ms_block">
            <div class="ms_info">
              <span class="name">{{ item?.msgCustomType === 1 ? item?.groupName : item.nickName }}</span>
              <span class="time" :key="item?.timestamp">{{ time(item) }}</span>
            </div>
            <div class="ms_num">
              <span class="ms_first" v-if="item?.msgType === 'IMAGE'">[图片]</span>
              <span class="ms_first" v-if="item?.msgType === 'CARD'">[群聊邀请]</span>
              <span class="ms_first"
                v-if="(item?.msgType === 'TEXT' || item?.msgType === 'ALERT' || item?.msgType === 'REVOKE')"
                v-html="emojiTest(item?.lastMsg)">
              </span>
              <span class="has_ms" v-if="(item?.hasRead !== 0 && item?.lastMsg !== '' && item?.disturb === 'N')">{{
                item?.hasRead
              }}</span>
              <el-icon v-if="item?.disturb === 'Y'" style="color: #515151;">
                <MuteNotification />
              </el-icon>
            </div>
          </section>
        </li>
      </div>
    </ul>
  </aside>
</template>
<script>
import Search from '@/components/Search.vue';
import SearchAddAction from '@/components/SearchAddAction.vue';
import { defineComponent, onMounted } from 'vue';
import { computed, ref, isRef, watch } from 'vue'
import { useVirtualList } from 'vue-hooks-plus'
import { db } from "@/config/data";
import { useObservable } from "@vueuse/rxjs";
import { liveQuery } from "dexie";
import { setFriendTopState, setFriendDisturb } from '@/server/friend'
import { setGroupTopState, setGroupDisturb } from '@/server/group'
import dayjs from 'dayjs';
import { useStore } from 'vuex';
import { useNetwork } from 'vue-hooks-plus'
import IsToday from 'dayjs/plugin/isToday'
import IsYesterday from 'dayjs/plugin/isYesterday'
dayjs.extend(IsToday)
dayjs.extend(IsYesterday)
export default defineComponent({
  name: "Panner",
  setup (props, { emit }) {
    const store = useStore()
    const conversation = useObservable(liveQuery(() => db.conversation?.toArray() || []))
    const selectSession = computed(() => store.state.selectSession)
    const conversationData = computed(() => {
      const data = [...(conversation.value || [])]
      const topData = data?.filter(row => row?.top === 'Y')
      const otherData = data?.filter(row => row?.top === 'N' || !row?.top)
      topData.sort((a, b) => b?.timestamp - a?.timestamp)
      otherData.sort((a, b) => b?.timestamp - a?.timestamp)
      return [...topData, ...otherData]
    })
    const wrapperRef = ref()
    const [list, container] = useVirtualList(conversationData, {
      wrapperTarget: wrapperRef,
      itemHeight: 68 + 4,
      overscan: 10,
    })
    const time = (item) => {
      if (dayjs(item?.timestamp).isToday()) return dayjs(item?.timestamp).format('HH:mm')
      if (dayjs(item?.timestamp).isYesterday()) return '昨天' + dayjs(item?.timestamp).format('HH:mm')
      return dayjs(item?.timestamp).format('MM/DD HH:mm')
    }

    const selectAction = async (item) => {
      store.commit('saveSelectSession', { ...item })
      await db.conversation.update(item?.id, { hasRead: 0 })
    }

    const networkState = useNetwork()
    const emoji = (text) => {
      Array.from(new Array(59)).forEach((v, r) => {
        const str = `[f0${r < 10 ? ('0' + r) : r}]`
        if (text.includes(str)) {
          text = text.replaceAll(str, `<img src="local-media://emoji/emoji_${r}@3x.png" class='emoji' style='width:15px;height:15px'/>`)
        }
      })
      return text
    }
    const emojiTest = (text) => {
      try {
        let t = JSON.parse(text)
        if (t?.content?.includes('http')) return '[图片]'
        return emoji(t?.content)
      } catch (error) {
        return emoji(text)
      }
    }


    // 列表操作
    const openRightMenu = async (item) => {
      const bands = await db.conversation.get({ uuid: item.uuid })
      const topText = bands?.top === 'Y' ? '取消置顶' : '置顶'
      const disturbText = bands?.disturb === 'Y' ? '开启消息提醒' : "消息免打扰"
      const isGroup = bands?.msgCustomType === 1
      const topAction = {
        label: topText,
        click: async () => {
          const top = bands?.top === 'Y' ? "N" : "Y"
          let res = null
          if (!isGroup) {
            res = await setFriendTopState({ top, userId: bands?.userId })
          } else {
            res = await setGroupTopState({ status: top, groupId: bands?.groupId })
          }
          if (res.code === 200) {
            await db.conversation.update(item?.id, { top })
          }
        }
      }
      const deleteAction = {
        label: "删除聊天",
        click: async () => {
          await db.conversation.where({ uuid: item.uuid })?.delete()
          await db.groupInfo.where({ uuid: item.uuid })?.delete()
          await db.privateChat.where({ uuid: item.uuid })?.delete()
          await db.groupChat.where({ uuid: item.uuid })?.delete()
          store.commit('saveSelectSession', {})
        }
      }

      const donDisturbAction = {
        label: disturbText,
        click: async () => {
          const disturb = bands?.disturb === 'Y' ? "N" : "Y"
          let res = null
          if (!isGroup) {
            res = await setFriendDisturb({ disturb, userId: bands?.userId })
          } else {
            res = await setGroupDisturb({ groupId: bands?.groupId, status: disturb })
          }
          if (res?.code === 200) {
            await db.conversation.where({ uuid: item.uuid }).modify({ disturb })
          }
        }
      }
      let actions = {
        topAction,
        deleteAction,
        donDisturbAction
      }
      if (isGroup) {
        const groupInfo = await db.groupInfo.get({ uuid: item?.uuid })
        if (groupInfo?.alertSubdivideType === 500) {
          // 已经退出群聊,只能删除了
          actions = { deleteAction }
        }
      }

      window.electronAPI.openRightClickMenu(Object.values(actions))
    }
    const dragstart = (e) => {
      console.log(e)
    }
    return {
      dragstart,
      list, container, wrapperRef,
      time,
      selectAction,
      selectSession,
      networkState,
      emojiTest,
      openRightMenu
    }
  },
  components: {
    SearchAddAction,
    Search,
  }
})
</script>

<style scoped lang="less">
@import url('./styles.less');
</style>
